<?php
/***********************************************************
 * 留言管理
 * @作者 pcfcms <1131680521@qq.com>
 * @版权 广州市春风科技有限公司
 * @主页 http://www.pcfcms.com
 * @时间 2019年12月21日
***********************************************************/
namespace app\admin\controller;
use think\facade\Db;
use think\facade\Session;
use think\facade\Request;
use think\facade\Cache;
class Guestbook extends Base
{
    public $popedom = '';
    private $field_type_list;
    public function initialize() {
        parent::initialize();
        $ctl_act = Request::controller().'/index';
        $this->popedom = appfile_popedom($ctl_act);
        $this->field_type_list = [
            'text'          => '单行文本',
            'multitext'     => '多行文本',
            'radio'         => '单选项',
            'checkbox'      => '多选项',
            'select'        => '下拉框',
            'switch'        => '开关',
        ];
    }

    public function index()
    {
        //验证权限
        if(!$this->popedom["list"]){
            return $this->errorNotice(config('params.auth_msg.list'),true,3,false);
        }
        if (Request::isAjax()) {
            $post = input('param.');
            if(isset($post['limit'])){
                $limit = $post['limit'];
            }else{
                $limit = 10;
            }
            $list = Db::name('guestbook')->paginate($limit);
            
            $newdata = $list->items();
            foreach ($newdata as $key => $value) {
                $newdata[$key]['attrcount'] = Db::name('guestbook_attr')->where(['form_id'=>$value['id'],'is_del'=>0])->count();
                $newdata[$key]['listcount'] = Db::name('guestbook_list')->where(['form_id'=>$value['id'],'is_del'=>0])->count();
            }
            $result = ['code' => 0, 'data' => $newdata,'count'=> $list->total()];
            return $result;
        }
        return $this->fetch();
    }

    public function add()
    {
        if (Request::isPost()) {
            //验证权限
            if(!$this->popedom["add"]){
                if(config('params.auth_msg.test')){
                    $result = ['status' => false, 'msg' => config('params.auth_msg.pcfcms')];
                    return $result;
                }else{
                    $result = ['status' => false, 'msg' => config('params.auth_msg.add')];
                    return $result;                    
                }
            }
            $post = input('param.');
            $add_data = array();
            $add_data['title'] = isset($post['title']) ? $post['title'] : '';
            $add_data['need_login'] = isset($post['need_login']) ? $post['need_login'] : 0;
            $add_data['status'] = isset($post['status']) ? $post['status'] : 1;
            $add_data['add_time'] = time();  
            $insertId = Db::name('guestbook')->insertGetId($add_data);          
            if ($insertId) {
				if(isset($post['attr_name'])){
					foreach ($post['attr_name'] as $key => $value) {
						if (!empty($value)) {
							$attr_values = !empty($post['attr_values'][$key]) ? $post['attr_values'][$key] : '';
							// 去除中文逗号，过滤左右空格与空值、以及单双引号
							if (!empty($attr_values)) {
								$attr_values = str_replace('，', ',', $attr_values);
								$attr_values = func_preg_replace(['"','\''], '', $attr_values);
								$attr_values_arr = explode(',', $attr_values);
								foreach ($attr_values_arr as $k2 => $v2) {
									$tmp_val = trim($v2);
									if ('' == $tmp_val) {
										unset($attr_values_arr[$k2]);
										continue;
									}
									$attr_values_arr[$k2] = trim($v2);
								}
								$attr_values = implode(',', $attr_values_arr);
							}
							// 主要参数
							$attrData[$key]['attr_name']      = trim($value); //字段名称
							$attrData[$key]['form_id']         = $insertId; //表单id
							$attrData[$key]['input_type']       = trim($post['input_type'][$key]);//字段类型
							$attrData[$key]['attr_values']       = $attr_values; //可选值
							$attrData[$key]['is_fill']      = 1 ;//是否必填
							$attrData[$key]['sort_order']      = trim($post['sort_order'][$key]); //排序
							$attrData[$key]['add_time']    = time();
						}
					}	
					$is_true = Db::name('guestbook_attr')->insertAll($attrData);
					if (!$is_true){
						Db::name('guestbook')->where("id",$insertId)->delete();
						$result = ['status' => false, 'msg' => '添加失败'];
						return $result;
					}									
				}
                $result = ['status' => true, 'msg' => '添加成功','url'=>Request::baseFile().'/Guestbook/index'];
                return $result;
            } else {
                $result = ['status' => false, 'msg' => '添加失败'];
                return $result;
            }
        }
        // 字段类型
        $field_type_html = '<select name="input_type[]" lay-ignore>';
        foreach ($this->field_type_list as $key => $val) {
            $field_type_html .= '<option value="'.$key.'">'.$val.'</option>';
        }
        $field_type_html .= '</select>';
        $this->assign('field_type_html',$field_type_html); 
        return $this->fetch();
    }

    public function edit()
    {   
        if (Request::isPost()) {
            //验证权限
            if(!$this->popedom["modify"]){
                if(config('params.auth_msg.test')){
                    $result = ['status' => false, 'msg' => config('params.auth_msg.pcfcms')];
                    return $result;
                }else{
                    $result = ['status' => false, 'msg' => config('params.auth_msg.modify')];
                    return $result;                    
                }
            } 
            $post = input('param.');
            $add_data = array();
            $add_data['id'] = $post['id'];
            $add_data['title'] = isset($post['title']) ? $post['title'] : '';
            $add_data['need_login'] = isset($post['need_login']) ? $post['need_login'] : 0;
            $add_data['status'] = isset($post['status']) ? $post['status'] : 1;
            $add_data['update_time'] = time();
            $p = Db::name('guestbook')->where('id', $add_data['id'])->data($add_data)->update();
            if ($p) {
                $addData = [];
                $editData = [];
                $id_arr = [];
                if(isset($post['attr_id'])){
                    foreach ($post['attr_id'] as $key => $value) {
                        $attr_values = !empty($post['attr_values'][$key]) ? $post['attr_values'][$key] : '';
                        // 去除中文逗号，过滤左右空格与空值、以及单双引号
                        if (!empty($attr_values)) {
                            $attr_values = str_replace('，', ',', $attr_values);
                            $attr_values = func_preg_replace(['"','\''], '', $attr_values);
                            $attr_values_arr = explode(',', $attr_values);
                            foreach ($attr_values_arr as $k2 => $v2) {
                                $tmp_val = trim($v2);
                                if ('' == $tmp_val) {
                                    unset($attr_values_arr[$k2]);
                                    continue;
                                }
                                $attr_values_arr[$k2] = trim($v2);
                            }
                            $attr_values = implode(',', $attr_values_arr);
                        }
                        if (empty($value)) {
                            $addData[] = [
                                'attr_name'=>trim($post['attr_name'][$key]),
                                'form_id'=>$post['id'],
                                'input_type'=> isset($post['input_type'][$key]) ? $post['input_type'][$key]:'' ,
                                'attr_values'=>$attr_values,
                                'is_fill' => 1,
                                'sort_order'=>trim($post['sort_order'][$key]),
                                'add_time'=>time()
                            ];
                        }else{
                            $editData[] = [
                                'attr_id'=>$value,
                                'attr_name'=>trim($post['attr_name'][$key]),
                                'form_id'=>$post['id'],
                                'input_type'=> isset($post['input_type'][$key]) ? $post['input_type'][$key]:'' ,
                                'attr_values'=>$attr_values,
                                'is_fill' => 1,
                                'sort_order'=>trim($post['sort_order'][$key]),
                                'update_time'=>time()
                            ];
                            $id_arr[] = $value;
                        }
                    }
                    if (!empty($id_arr)){
                        $allid = Db::name('guestbook_attr')->field('attr_id')->where('form_id', $post['id'])->select()->toArray();
                        $allid1 = [];
                        foreach ($allid as $key => $v) {
                            $allid1[$key] = $v['attr_id'];
                        }
                        unset($allid);
                        foreach ($allid1 as $k => $val) {
                            if (!in_array($val,$id_arr)) {
                               Db::name('guestbook_attr')->where('form_id', $post['id'])->where('attr_id',$val)->delete();
                            }
                        }
                    }
                    if (!empty($editData)){
                        foreach ($editData as $k => $v) {
                            Db::name('guestbook_attr')->update($v);
                        }
                    }
                    if (!empty($addData)){
                        Db::name('guestbook_attr')->insertAll($addData);
                    }                    
                }else{
                    Db::name('guestbook_attr')->where('form_id', $post['id'])->delete();
                }
            } else {
                $result = ['status' => false, 'msg' => '修改失败'];
                return $result;
            }
            $result = ['status' => true, 'msg' => '修改成功','url'=>Request::baseFile().'/Guestbook/index'];
            return $result;
        }
        if (Request::isAjax()) {
            $form_id = input('param.form_id/d',0);
            $form_attr_list = Db::name('guestbook_attr')->where("form_id={$form_id} and is_del=0")->select();
            $result = ['code' => 0, 'data' => $form_attr_list,'count'=>''];
            return $result;
        }
        $id = input('param.id/d',0); 
        $info = Db::name('guestbook')->where('id', $id)->find();
        $assign_data['info'] = $info;
        // 字段类型
        $field_type_html = '<select name="input_type[]" lay-ignore>';
        foreach ($this->field_type_list as $key => $val) {
            $field_type_html .= '<option value="'.$key.'">'.$val.'</option>';
        }
        $field_type_html .= '</select>'; 
        $assign_data['field_type_html'] = $field_type_html;
        $this->assign($assign_data); 
        return $this->fetch('edit');
    }

    public function del()
    {
        if (Request::isAjax()) {
            //验证权限
            if(!$this->popedom["delete"]){
                if(config('params.auth_msg.test')){
                    $result = ['code' => 0, 'msg' => config('params.auth_msg.pcfcms')];
                    return $result;
                }else{
                    $result = ['code' => 0, 'msg' => config('params.auth_msg.delete')];
                    return $result;                    
                }
            } 
            $id_arr = input('del_id/a');
            $id_arr = eyIntval($id_arr);
            if(is_array($id_arr) && !empty($id_arr)){
                $p = Db::name('guestbook')->where('id','IN',$id_arr)->delete();
                if ($p) {
                    Db::name('guestbook_attr')->where('form_id','IN',$id_arr)->delete();
                    Db::name('guestbook_list')->where('form_id','IN',$id_arr)->delete();
                    Db::name('guestbook_value')->where('form_id','IN',$id_arr)->delete();
                    $result = ['code' => 1, 'msg' => '删除成功！'];
                    return $result;
                } else {
                    $result = ['code' => 0, 'msg' => '参数有误'];
                    return $result;
                }
            } else {
                $result = ['code' => 0, 'msg' => '参数有误'];
                return $result;
            }
        }       
    }

    // 留言内容
    public function bookcontent()
    {
        //验证权限
        if(!$this->popedom["list"]){
            return $this->errorNotice(config('params.auth_msg.list'),true,3,false);
        }
        if (Request::isAjax()) {
            $post = input('param.');
            $formname = Db::name('guestbook')->where('id',$post['id'])->value('title');
            if(isset($post['limit'])){
                $limit = $post['limit'];
            }else{
                $limit = 10;
            }
            $list = Db::name('guestbook_list')->where('form_id',$post['id'])->paginate($limit);
            $newdata = $list->items();
            foreach ($newdata as $key => $value) {
                $newdata[$key]['add_time'] = pcftime($value['add_time']);
                $newdata[$key]['formname'] = $formname;
            }
            $result = ['code' => 0, 'data' => $newdata,'count'=> $list->total()];
            return $result;
        }
        $this->assign('form_id',input('param.id'));
        return $this->fetch('content');
    }

    //删除提交内容
    public function condel()
    {
        if (Request::isAjax()) {
            //验证权限
            if(!$this->popedom["delete"]){
                if(config('params.auth_msg.test')){
                    $result = ['code' => 0, 'msg' => config('params.auth_msg.pcfcms')];
                    return $result;
                }else{
                    $result = ['code' => 0, 'msg' => config('params.auth_msg.delete')];
                    return $result;                    
                }
            } 
            $id_arr = input('del_id/a');
            $id_arr = eyIntval($id_arr);
            if(is_array($id_arr) && !empty($id_arr)){
                $p = Db::name('guestbook_list')->where('list_id','IN',$id_arr)->delete();
                if ($p) {
                    Db::name('guestbook_value')->where('list_id','IN',$id_arr)->delete();
                    $result = ['code' => 1, 'msg' => '删除成功！'];
                    return $result;
                } else {
                    $result = ['code' => 0, 'msg' => '参数有误'];
                    return $result;
                }
            } else {
                $result = ['code' => 0, 'msg' => '参数有误'];
                return $result;
            }
        } 
    } 

    //查看详细提交内容
    public function conedit()
    {
        $list_id = input('id/d',0);
        // 表单内容信息
        $guestbook_list = Db::name('guestbook_list')->where('list_id',$list_id)->find();
        $guestbook_list['add_time'] = pcftime($guestbook_list['add_time']);
        $guestbook_attr_list = Db::name("guestbook_attr")->where(['form_id' => $guestbook_list['form_id'],'is_del' => 0])->order("sort_order asc")->select()->toArray();
        $value_list = Db::name('guestbook_value')->where('list_id',$list_id)->select()->toArray();
        $value_list = array_combine(array_column($value_list, 'attr_id'), $value_list);

        $guestbook_attr_list1  = array();
        foreach ($guestbook_attr_list as $key => $value) {
          foreach ($value_list as $k => $val) {
              if($value['attr_id'] == $val['value_id']){
                 $guestbook_attr_list1[] = $guestbook_attr_list[$key];
              }
          }
        }
        $assign_data = [
            'guestbook_list' => $guestbook_list,
            'guestbook_attr_list' => $guestbook_attr_list1,
            'value_list' => $value_list,
        ];
        $this->assign($assign_data);
        return $this->fetch('conedit');
    }

    public function getcode()
    {
        $form_id = input('id/d',0);
        if (!empty($form_id)) {
            $form_list = Db::name('guestbook')->where('id',$form_id)->find();
            $form_attr_list = Db::name("guestbook_attr")->where([
                'form_id'   => $form_list['id'],
                'is_del'    => 0,
            ])->order("sort_order asc")->select()->toArray();
            $content = '{gzpcf:form formid="'.$form_list['id'].'"}'."\n";
            $content .= '<form method="post" id="{$field.form_name}">'."\n";
            foreach ($form_attr_list as $key=>$val){
                $attr_id = $val['attr_id'];
                switch ($val['input_type']){
                    case "multitext": // 多行文本
                        $content .= '<textarea rows="2" cols="60" id="{$field.attr_'.$attr_id.'}" name="{$field.attr_'.$attr_id.'}" placeholder="{$field.itemname_'.$attr_id.'}"></textarea>'."\n";
                        break;
                    case "checkbox": // 多选
                        $content .= '{gzpcf:volist name="$field.options_'.$attr_id.'" id="attr"}'."\n";
                        $content .= '<input type="checkbox" id="{$field.attr_'.$attr_id.'}" name="{$field.attr_'.$attr_id.'}[]" value="{$attr.value}">{$attr.value}'."\n";
                        $content .= '{/gzpcf:volist}'."\n";
                        break;
                    case "radio": // 单选
                        $content .= '{gzpcf:volist name="$field.options_'.$attr_id.'" id="attr"}'."\n";
                        $content .= '<input type="radio" id="{$field.attr_'.$attr_id.'}" name="{$field.attr_'.$attr_id.'}" value="{$attr.value}">{$attr.value}'."\n";
                        $content .= '{/gzpcf:volist}'."\n";
                        break;
                    case "switch": // 开关
                        $content .= '<input type="radio" id="{$field.attr_'.$attr_id.'}" name="{$field.attr_'.$attr_id.'}" value="是">是&nbsp;<input type="radio" id="{$field.attr_'.$attr_id.'}" name="{$field.attr_'.$attr_id.'}" value="否">否'."\n";
                        break;
                    case "select": // 下拉选择
                        $content .= '<select id="{$field.attr_'.$attr_id.'}" name="{$field.attr_'.$attr_id.'}">'."\n";
                        $content .= '{gzpcf:volist name="$field.options_'.$attr_id.'" id="attr"}'."\n";
                        $content .= '<option value="{$attr.value}">{$attr.value}</option>'."\n";
                        $content .= '{/gzpcf:volist}'."\n";
                        $content .= '</select>'."\n";
                        break;
                    default:  // 单行文本
                        $content .= '<input type="text" id="{$field.attr_'.$attr_id.'}" name="{$field.attr_'.$attr_id.'}" placeholder="{$field.itemname_'.$attr_id.'}" >'."\n";
                        break;
                }
            }
            $content .=' <div onclick="tijiao();">提交</div>'."\n";
            $content .='{:token_field("__token__", "md5")}'."\n";
            $content .='{$field.hidden|raw}'."\n";
            $content .='</form>'."\n";
            $content .='{/gzpcf:form}';
            $assign_data = ['content' => $content];
            $this->assign($assign_data);
            return $this->fetch('code');
        }
    }
    
}